package org.eclipse.soc.ide4edu.assignment.wizards;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.soc.ide4edu.assignment.operations.DownloadOperation;
import org.eclipse.soc.ide4edu.assignment.operations.LoginMap;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;

public class AssignmentDownloadWizard extends Wizard implements INewWizard {

	AssignmentDownloadWizardPage1 general;
	AssignmentDownloadWizardPage2 login;

	@Override
	public void addPages() {
		general = new AssignmentDownloadWizardPage1("General Information");
		addPage(general);

		login = new AssignmentDownloadWizardPage2("Login");
		addPage(login);
	}

	private String generateLink() {

		String link = general.getServerURL();
		String serverName = general.getServerName();

		if (serverName.equals("Moodle")) {

			link += "/file.php/" + general.getCourseID() + "/"
					+ general.getAssignmentName() + ".zip";
			return link;

		}

		return null;
	}

	private String getDownloadLink() {

		if (general.getUserChoice().equals("direct"))
			return general.getDirectURL();

		if (general.getUserChoice().equals("generate"))
			return generateLink();

		return null;
	}

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {

	}

	private void openBrowser(String link) {
		try {

			IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport()
					.createBrowser((1 << 5) | (1 << 1) | (1 << 2),
							"Assignment", "Assignment Download", "Assignment");
			browser.openURL(new URL(link));

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (PartInitException e) {
			e.printStackTrace();
		}

	}

	private void performAuthenticationAndDownload(String choice, String link)
			throws IOException {

		if (choice.equals("eclipse")) {
			final String username = login.getUsername();
			final String password = login.getPassword();

			LoginMap lMap = new LoginMap();

			URL url = lMap.getLoginUrl(general.getServerURL(), general
					.getServerName());

			DownloadOperation downloadOperation = new DownloadOperation(link,
					url);
			downloadOperation.authenticate(username, password);
			downloadOperation.downloadAssignment();

		}

		if (choice.equals("browser")) {
			openBrowser(link);
		}

	}

	@Override
	public boolean performFinish() {

		try {
			String link = getDownloadLink();
			String choice = login.getUserChoice();
			performAuthenticationAndDownload(choice, link);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return true;
	}

}
